package com.lumm.services.impl;

import com.lumm.dao.DetailsMapper;
import com.lumm.dao.FavourMapper;
import com.lumm.dao.UserMapper;
import com.lumm.model.*;
import com.lumm.services.UserService;
import com.lumm.util.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import static com.lumm.util.FileUtil.getCellFormatValue;

@Service("UserServiceImp")

public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DetailsMapper detailsMapper;

    @Autowired
    private FavourMapper favourMapper;

    private UserExample userExample = new UserExample();

    public User querybyUserId(int userId) {

        return userMapper.selectByPrimaryKey(userId);
    }

    public int insert(User user) {
        return 0;
    }

    public int login(String id, String password) {
        User user;
        userExample.clear();
        if (EmailUtil.checkEmailFormat(id)) {
            userExample.or().andEmailEqualTo(id);
            if (userMapper.countByExample(userExample) > 0)
                user = userMapper.selectByExample(userExample).get(0);
            else
                user = null;
        } else {
            try {
                user = userMapper.selectByPrimaryKey(Integer.parseInt(id));
            } catch (NumberFormatException e) {
                e.printStackTrace();
                user = null;
            }
        }
        if (user == null)
            return 5;
        if (user.getPassword().equals(PasswordUtil.encryptPassword(password)))
            return user.getUserId();
        return 4;
    }

    public String sendEmailVcode(String toAddress, String action) {
        String vcode = String.valueOf(new Random().nextInt(899999) + 100000);

        System.out.println("vcode:" + vcode);

        final EmailUtil.Email email = new EmailUtil.Email();

        email.toAddress = toAddress;
        switch (action) {
            case "register":
                email.toUser = WebsiteConfig.SITE_NAME + "新用户";
                email.subject = "注册" + WebsiteConfig.SITE_NAME + "新用户";
                email.content = "您正在注册" + WebsiteConfig.SITE_NAME + "新用户，" + "验证码为" + vcode + "（若不是本人操作请忽略）。";
                break;
            case "resetPassword":
                email.toUser = WebsiteConfig.SITE_NAME + "用户";
                email.subject = "重置密码";
                email.content = "尊敬的" + WebsiteConfig.SITE_NAME + "用户，您正在重置" + WebsiteConfig.SITE_NAME + "的登录密码，验证码为" + vcode + "（若不是本人操作请忽略）。";
                break;
        }
        new Thread() {
            @Override
            public void run() {
                EmailUtil.sendEmail(email.toAddress, email.toUser, email.subject, email.content);
            }
        }.start();
        return vcode;
    }

    public boolean checkEmailAvailability(String email) {
        UserExample userExample = new UserExample();
        userExample.or().andEmailEqualTo(email);
        return !(userMapper.selectByExample(userExample).size() > 0);
    }

    @Transactional
    @Override
    public User createNewUser(String email, String password, String gender, String name, Date birthday, String phoneNum, short maritalStatus) {
        User user = new User();
        user.setEmail(email);
        user.setPassword(PasswordUtil.encryptPassword(password));
        user.setGender(gender);
        user.setNickname(name);
        user.setIdNum("");
        user.setAccountStatus(Short.valueOf("1"));
        user.setName(name);
        user.setNickname(name);
        user.setPhoneNum(phoneNum);
        user.setMaritalStatus(maritalStatus);
        user.setBirthday(birthday);
        user.setRegisterTime(new Date(System.currentTimeMillis()));
        user.setActiveDays(0);
        user.setCoins(10);
        user.setActiveDays(0);
        user.setActiveValue(0);
        user.setIdNum("未设置");
        user.setFansNum(0);
        user.setFollowNum(0);
        user.setPraisedNum(0);
        user.setPopularity(0);
        user.setProfilePhoto("defaultProfilePhoto.png");
        user.setVipLevel((short) 0);
        user.setLastLoginTime(user.getRegisterTime());
        user.setSelfIntro("我们穿越大地只是经历生活！");
        userMapper.insert(user);
        UserExample userExample = new UserExample();
        userExample.or().andEmailEqualTo(email);
        user = userMapper.selectByExampleWithBLOBs(userExample).get(0);
        detailsMapper.insert(Details.createDefault(user.getUserId()));
        favourMapper.insert(Favour.createDefault(user.getUserId()));
        return user;
    }

    @Override
    public Details getUserDetails(int userId) {
        Details details = detailsMapper.selectByPrimaryKey(userId);
        return details;
    }

    @Override
    public Favour getUserFavour(int userId) {
        Favour favour = favourMapper.selectByPrimaryKey(userId);
        return favour;
    }

    @Override
    public User resetPassword(String email, String password) {

        userExample.clear();
        userExample.or().andEmailEqualTo(email);

        List<User> users = userMapper.selectByExample(userExample);

        if (users.size() < 1)
            return null;

        User user = users.get(0);

        user.setPassword(PasswordUtil.encryptPassword(password));

        userMapper.updateByPrimaryKey(user);

        return user;
    }

    @Override
    public int getUserCount() {
        UserExample userExample = new UserExample();
        return userMapper.countByExample(userExample);
    }

    @Override
    public List<User> getUserList(int offset, int count) {
        UserExample userExample = new UserExample();
        userExample.setOrderByClause("user_id DESC limit " + offset + "," + count);
        return userMapper.selectByExampleWithBLOBs(userExample);
    }

    @Override
    public int addNewUser(String email, String gender, String name, Date birthday, String phoneNum, short maritalStatus) {

        if (!checkEmailAvailability(email))
            return 2;

        return createNewUser(email, "123456", gender, name, birthday, phoneNum, maritalStatus).getUserId();
    }

    @Override
    public int deleteUser(int userId) {
        return userMapper.deleteByPrimaryKey(userId);
    }

    @Override
    public int updateUserInfo(int userId, String gender, String name, Date birthday, String phoneNum, short maritalStatus) {

        User oldUserInfo = userMapper.selectByPrimaryKey(userId);

        if (oldUserInfo == null)
            return 5;

        oldUserInfo.setPhoneNum(phoneNum);
        oldUserInfo.setNickname(name);
        oldUserInfo.setBirthday(birthday);
        oldUserInfo.setMaritalStatus(maritalStatus);
        oldUserInfo.setGender(gender);
        return userMapper.updateByPrimaryKey(oldUserInfo);
    }

    // name gender maritalStatus email phoneNum birthday
    @Override
    public List<User> importUserList(File listFile) {

        if (listFile == null)
            return null;

        Workbook workbook = FileUtil.readExcel(listFile.getAbsolutePath());

        if (workbook == null)
            return null;

        Sheet sheet = workbook.getSheetAt(0);
        //获取最大行数
        int rownum = sheet.getPhysicalNumberOfRows();
        //获取第一行
        Row row = sheet.getRow(0);

        List<User> importSuccessUsers = new ArrayList<>();

        int successCount = 0;

        for (int i = 1; i < rownum; i++) {
            row = sheet.getRow(i);
            if (row != null) {
                User user = new User();

                user.setName(row.getCell(0).getStringCellValue());

                user.setGender(row.getCell(1).getStringCellValue());

                int index = Constants.stringIndexOfArray(row.getCell(2).getStringCellValue(), Constants.maritalStatus);
                user.setMaritalStatus(index == -1 ? 0 : (short) index);

                user.setEmail(row.getCell(3).getStringCellValue());

                user.setPhoneNum("" + (long) row.getCell(4).getNumericCellValue());

                user.setBirthday(row.getCell(5).getDateCellValue());

                try {

                    if (!checkEmailAvailability(user.getEmail()))
                        continue;

                    user = createNewUser(user.getEmail(), "123456", user.getGender(), user.getName(), user.getBirthday(), user.getPhoneNum(), user.getMaritalStatus());


                    //user.getBirthday()

                    if (user != null)
                        importSuccessUsers.add(user);

                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
            } else {
                break;
            }
        }


        return importSuccessUsers;
    }

    @Override
    public List<RecommendItem> searchUserByKeyword(String keyword) {

        UserExample userExample = new UserExample();

        DetailsExample detailsExample = new DetailsExample();

        userExample.setOrderByClause("rand()");

        userExample.or().andEmailLike("%" + keyword + "%");

        userExample.or().andNicknameLike("%" + keyword + "%");
        try {
            int userId = Integer.parseInt(keyword);
            userExample.or().andUserIdEqualTo(userId);
        } catch (NumberFormatException e) {

        }

        List<User> users = userMapper.selectByExampleWithBLOBs(userExample);

        List<RecommendItem> recommendItems = new ArrayList<>();
        for (User oneUser : users) {

            DetailsWithBLOBs details = detailsMapper.selectByPrimaryKey(oneUser.getUserId());
            RecommendItem recommendItem = new RecommendItem();
            recommendItem.setUserId(oneUser.getUserId());
            recommendItem.setGender(oneUser.getGender());
            recommendItem.setSelfIntro(oneUser.getSelfIntro());
            recommendItem.setVipLevel(oneUser.getVipLevel());
            recommendItem.setName(oneUser.getName());

            try {
                recommendItem.setAge(DateUtil.getAge(oneUser.getBirthday()));
            } catch (Exception e) {
                e.printStackTrace();
                recommendItem.setAge(0);
            }

            if (details != null) {
                recommendItem.setDomicile(details.getDomicile());
                recommendItem.setHeight(details.getHeight());
                recommendItem.setEducation(details.getEducation());
                recommendItem.setEducation(details.getEducation());
                recommendItem.setMonthlySalary(details.getMonthlySalary());
                recommendItem.setWeight(details.getWeight());
                recommendItem.setHobby(details.getHobby());
                recommendItem.setLoveDeclaration(details.getLoveDeclaration());
            }
            recommendItems.add(recommendItem);
        }

        //userExample.or().("%"+keyword+"%");

        return recommendItems;
    }

    @Override
    public List<User> getUserByKeyword(String keyword) {

        UserExample userExample = new UserExample();

        DetailsExample detailsExample = new DetailsExample();

        userExample.setOrderByClause("rand()");

        userExample.or().andEmailLike("%" + keyword + "%");

        userExample.or().andNicknameLike("%" + keyword + "%");
        try {
            int userId = Integer.parseInt(keyword);
            userExample.or().andUserIdEqualTo(userId);
        } catch (NumberFormatException e) {

        }

        List<User> users = userMapper.selectByExampleWithBLOBs(userExample);

        return users;
    }

    @Transactional
    @Override
    public int updateUserInfo(User user, DetailsWithBLOBs details, Favour favour) {

        User oldUser = userMapper.selectByPrimaryKey(user.getUserId());

        oldUser.setName(user.getName());
        oldUser.setNickname(user.getNickname());
        oldUser.setIdNum(user.getIdNum());
        oldUser.setPhoneNum(user.getPhoneNum());
        oldUser.setBirthday(user.getBirthday());
        oldUser.setEmail(user.getEmail());
        oldUser.setSelfIntro(user.getSelfIntro());

        DetailsWithBLOBs oldDetails = detailsMapper.selectByPrimaryKey(user.getUserId());

        oldDetails.setDomicile(details.getDomicile());
        oldDetails.setEducation(details.getEducation());
        oldDetails.setMajor(details.getMajor());
        oldDetails.setHeight(details.getHeight());
        oldDetails.setWeight(details.getWeight());
        oldDetails.setOrganizationType(details.getOrganizationType());
        oldDetails.setMonthlySalary(details.getMonthlySalary());
        oldDetails.setHobby(details.getHobby());
        oldDetails.setLoveDeclaration(details.getLoveDeclaration());


        return userMapper.updateByPrimaryKey(oldUser) * detailsMapper.updateByPrimaryKey(oldDetails) * favourMapper.updateByPrimaryKeySelective(favour);
    }
}
